<template>
  <view class="chat-messages" ref="messagesContainer">
    <view 
      v-for="(message, index) in messages" 
      :key="index"
      class="message-item"
      :class="message.role"
    >
      <view class="message-avatar">
        <text class="avatar-icon">{{ message.role === 'user' ? '👤' : '🤖' }}</text>
      </view>
      <view class="message-content">
        <view class="message-header">
          <text class="message-sender">{{ message.role === 'user' ? '我' : 'AI助手' }}</text>
          <text class="message-time">{{ formatTime(message.timestamp) }}</text>
        </view>
        <view class="message-text">
          <!-- 如果是markdown格式，使用MarkdownRenderer组件 -->
          <MarkdownRenderer 
            v-if="message.isMarkdown" 
            :content="message.content"
          />
          <!-- 普通文本 -->
          <text v-else>{{ message.content }}</text>
        </view>
        <!-- 命令建议 -->
        <view class="message-actions" v-if="message.actions && message.actions.length > 0">
          <button 
            v-for="action in message.actions" 
            :key="action.label"
            class="action-btn"
            @click="onActionClick(action)"
          >
            {{ action.label }}
          </button>
        </view>
      </view>
    </view>

    <!-- 输入中提示 -->
    <view class="message-item assistant typing" v-if="isTyping">
      <view class="message-avatar">
        <text class="avatar-icon">🤖</text>
      </view>
      <view class="message-content">
        <view class="typing-indicator">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import MarkdownRenderer from './MarkdownRenderer.vue'

export default {
  name: 'MessageList',
  components: {
    MarkdownRenderer
  },
  props: {
    messages: {
      type: Array,
      default: () => []
    },
    isTyping: {
      type: Boolean,
      default: false
    }
  },
  emits: ['action-click'],
  setup(props, { emit }) {
    // 格式化时间
    const formatTime = (timestamp) => {
      const date = new Date(timestamp)
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    /* 移除：Markdown解析已迁移到 MarkdownRenderer 组件
    const parseMarkdown = (markdown) => {
      if (!markdown) return ''
      
      let html = markdown
      
      // 转义HTML特殊字符
      html = html.replace(/&/g, '&amp;')
               .replace(/</g, '&lt;')
               .replace(/>/g, '&gt;')
      
      // 标题 (# ## ###)
      html = html.replace(/^### (.*$)/gim, '<h3 style="font-size: 16px; font-weight: bold; margin: 12px 0 8px 0; color: #303133;">$1</h3>')
      html = html.replace(/^## (.*$)/gim, '<h2 style="font-size: 18px; font-weight: bold; margin: 14px 0 10px 0; color: #303133;">$1</h2>')
      html = html.replace(/^# (.*$)/gim, '<h1 style="font-size: 20px; font-weight: bold; margin: 16px 0 12px 0; color: #303133;">$1</h1>')
      
      // 粗体 **text**
      html = html.replace(/\*\*(.*?)\*\*/g, '<strong style="font-weight: 600; color: #409eff;">$1</strong>')
      
      // 分割线 ---
      html = html.replace(/^---$/gim, '<hr style="border: none; border-top: 1px solid #e4e7ed; margin: 12px 0;" />')
      
      // 处理表格
      const lines = html.split('\n')
      let inTable = false
      let tableHtml = ''
      const processedLines = []
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim()
        
        // 检测表格行
        if (line.startsWith('|') && line.endsWith('|')) {
          if (!inTable) {
            inTable = true
            tableHtml = '<table style="width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 13px;">'
          }
          
          const cells = line.split('|').filter(cell => cell.trim() !== '')
          const isHeaderSeparator = cells.every(cell => /^[\s-:]+$/.test(cell))
          
          if (isHeaderSeparator) {
            continue
          }
          
          const isHeader = inTable && !tableHtml.includes('<tr')
          
          if (isHeader) {
            tableHtml += '<thead><tr style="background-color: #f5f7fa;">'
            cells.forEach(cell => {
              tableHtml += `<th style="border: 1px solid #e4e7ed; padding: 8px; text-align: center; font-weight: 600;">${cell.trim()}</th>`
            })
            tableHtml += '</tr></thead><tbody>'
          } else {
            tableHtml += '<tr style="background-color: #fff;">'
            cells.forEach((cell, idx) => {
              const align = idx === 0 ? 'left' : 'center'
              tableHtml += `<td style="border: 1px solid #e4e7ed; padding: 8px; text-align: ${align};">${cell.trim()}</td>`
            })
            tableHtml += '</tr>'
          }
        } else {
          if (inTable) {
            tableHtml += '</tbody></table>'
            processedLines.push(tableHtml)
            inTable = false
            tableHtml = ''
          }
          processedLines.push(line)
        }
      }
      
      if (inTable) {
        tableHtml += '</tbody></table>'
        processedLines.push(tableHtml)
      }
      
      html = processedLines.join('\n')
      html = html.replace(/\n\n/g, '<br/><br/>')
      html = html.replace(/\n/g, '<br/>')
      
      return `<div style="line-height: 1.6; color: #606266;">${html}</div>`
    }
    */
    
    const onActionClick = (action) => {
      emit('action-click', action)
    }
    
    return {
      formatTime,
      onActionClick
    }
  }
}
</script>

<style scoped>
/* 消息列表 */
.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  gap: 12px;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 36px;
  height: 36px;
  flex-shrink: 0;
  border-radius: 50%;
  background-color: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-item.user .message-avatar {
  background-color: #67c23a;
}

.avatar-icon {
  font-size: 20px;
}

.message-content {
  flex: 1;
  max-width: 80%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.message-item.user .message-content {
  align-items: flex-end;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.message-item.user .message-header {
  flex-direction: row-reverse;
}

.message-sender {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.message-time {
  font-size: 11px;
  color: #c0c4cc;
}

.message-text {
  padding: 12px 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.markdown-content {
  width: 100%;
  overflow-x: auto;
}

.markdown-content table {
  max-width: 100%;
  overflow-x: auto;
  display: block;
}

.message-item.user .message-text {
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
  color: #fff;
}

.message-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 6px 12px;
  background-color: #fff;
  border: 1px solid #409eff;
  border-radius: 4px;
  color: #409eff;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  background-color: #409eff;
  color: #fff;
}

/* 输入中提示 */
.typing-indicator {
  padding: 12px 16px;
  background-color: #fff;
  border-radius: 8px;
  display: flex;
  gap: 4px;
}

.typing-indicator .dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #909399;
  animation: typing 1.4s infinite;
}

.typing-indicator .dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator .dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>

